<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="pager.name" placeholder="角色名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        新增
      </el-button>
    </div>
    <el-row :gutter="10">
      <el-col :span="18">
        <el-table
          :data="list"
          highlight-current-row
          style="width: 100%"
          row-key="id"
          border
          @current-change="selectChanged"
        >
          <el-table-column
            type="index"
            label="序号"
            width="60"
          />
          <el-table-column
            prop="name"
            label="名称"
            width="150"
          />
          <el-table-column
            prop="remark"
            label="说明"
          />
          <el-table-column label="操作" width="240">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="warning"
                @click="$message('点击了设置权限按钮')"
              >分配权限</el-button>
              <el-button
                size="mini"
                @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button>

              <el-popconfirm
                class="btnspace"
                title="确定删除吗？"
                @onConfirm="handleDelete(scope.$index, scope.row)"
              >
                <el-button slot="reference" type="danger" size="mini">删除</el-button>
              </el-popconfirm>

            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination
          :current-page="pager.pageIndex"
          :page-sizes="[5, 8, 10, 15,20]"
          :agpe-size="pager.pageSize"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @current-change="pageChange"
          @size-change="sizeChange"
        />

      </el-col>
      <el-col :span="6">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>权限设置</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="setActions">设置</el-button>
          </div>
          <el-tree
            ref="tree"
            node-key="id"
            :props="props"
            :data="menus"
            show-checkbox
            @check-change="handleCheckChange"
          />
        </el-card>

      </el-col>
      <!-- 抽屉 -->
      <el-drawer :visible.sync="openWin">
        <template slot="title"><h3>{{ optype=="create"?'添加':'修改' }}</h3></template>
        <component :is="optype" :data="currentRole" @closeWin="closeDrawer" />
      </el-drawer>
    </el-row>
  </div>
</template>
<script>
import request from '@/utils/request'
import create from './create'
import edit from './edit'
export default {
  components: {
    create, edit
  },
  data() {
    return {
      list: [],
      menus: [],
      props: {
        label: 'title',
        isLeaf: 'leaf'
      },
      pager: {
        pageIndex: 1,
        pageSize: 5,
        name: ''
      },
      total: 0,
      openWin: false,
      optype: 'create',
      currentRole: {} // 当前选中的行
    }
  },
  created() {
    this.getList()
    this.getAllActions()
  },
  methods: {
    getList() {
      request({
        url: 'roles',
        method: 'get',
        params: this.pager
      }).then(res => {
        this.list = res.data
        this.total = res.total
      })
    },
    // 查询
    handleFilter() {
      this.getList()
    },
    // 新增按钮
    handleCreate() {
      this.optype = 'create'
      this.openWin = true
    },
    // 修改
    handleEdit(index, row) {
      this.currentRole = row
      this.optype = 'edit'
      this.openWin = true
    },
    // 删除
    async handleDelete(index, row) {
      await request({ url: 'roles/' + row.id, method: 'delete' })
      this.getList()
    },
    // 翻页
    pageChange(index) {
      this.pager.pageIndex = index
      this.getList()
    },
    // 调页数
    sizeChange(size) {
      this.pager.pageSize = size
      this.getList()
    },
    async getActions(pid) {
      return await request({
        url: '/functions/' + pid,
        method: 'get'
      })
    },
    // 关闭编辑窗口
    closeDrawer(isReflash) {
      this.openWin = false
      if (isReflash) {
        this.getList()
      }
    },
    // 选中不同的角色
    async selectChanged(row) {
      this.currentRole = row // 当前选中行
      // 清空选择的节点
      this.$refs.tree.setCheckedKeys([])
      // 获取角色的权限数组
      const ids = await request({ url: '/roles/getactions/' + row.id, method: 'get' })
      console.log(ids)
      ids.forEach(element => {
        var node = this.$refs.tree.getNode(element)
        if (node.isLeaf) {
          this.$refs.tree.setChecked(node, true)
        }
      })

      // 设置tree选中节点
      // this.$refs.tree.setCheckedKeys(ids)
    },
    // 加载权限tree
    async loadActions(node, resolve) {
      if (node.level === 0) {
        return resolve(await this.getActions(0))
      }
      if (node.level >= 1) {
        return resolve(await this.getActions(node.data.id))
      }
    },
    // 所有权限
    async getAllActions() {
      // 所有节点
      const actions = await request.get('/functions/GetAllActions')
      const roots = actions.filter(ele => {
        return ele.parentId === 0
      })
      roots.forEach(root => {
        this.setChildrenNodes(root, actions)
      })
      this.menus = roots
    },
    // 递归
    setChildrenNodes(node, actions) {
      node.children = []
      var children = actions.filter(ele => {
        return ele.parentId === node.id
      })
      children.forEach(e => {
        node.children.push(e)
        this.setChildrenNodes(e, actions)
      })
    },
    // 设置权限
    async setActions() {
      var aids = this.$refs.tree.getCheckedKeys() // 选中的id
      aids = aids.concat(this.$refs.tree.getHalfCheckedKeys())
      const roleId = this.currentRole.id
      console.log(aids)
      request.defaults.headers.common['Content-Type'] = 'application/json'
      await request.put('/roles/setActions/' + roleId, JSON.stringify(aids),
        { headers: { 'Content-Type': 'application/json' }})
      this.$message('设置完成')
    },
    handleCheckChange() {

    }
  }
}
</script>
<style scoped>
  .btnspace{
    margin-left: 10px;
  }
</style>
